templateCookiePrefix = "rt_";


function getSiteCfg() { 
    $.getJSON(
        "/api/tmpo/config_public/",
        function(json) {
            var val = 'POC: <a class="POCemail" href="mailto:' +
                      json.tmpo_poc_email + '">' + json.tmpo_poc_name +
                      '</a> Phone: (' + json.tmpo_poc_phone.substr(0,3) +
                      ') ' + json.tmpo_poc_phone.substr(3,3) + '-' + 
                      json.tmpo_poc_phone.substr(6,4);
            $("span.POCemail").append(val); 
        }
    );
}


function notifyMessage(id) {
    $.ajax({
        type: "GET",
        url: '/api/tmpo/commitment/notify/' + id + '/',
        error: function(){
            console.debug('Message failed.');
        },
        complete: function() {
            window.location.href = "/tmpo/form248/thanks/";
        }
    });
}


function getCommonLookups() {
    $.ajax({
        type: 'GET',
        url: '/api/tmpo/resources/',
        dataType: "json",
        success: function(json) {
            var val = '';
            $.each(json.drivers, function() {
	        val += '<input type="checkbox" value="' + this['id'] +
                       '" label="' + this['name'] + '" /> ' +
                       this['name'] + '<br />';
            });
            $("span[name='drivers']").append(val);
            val = '';
            $.each(json.vehicles, function() {
	        val += '<input type="checkbox" value="' + this['id'] +
                       '" label="' + this['vehicleno'] + '" /> ' +
                       this['vehicleno'] + '<br />';
            });
            $("span[name='vehicles']").append(val);
        },
        complete: function() {
            setProtoHTML();
            buildForm();
        }
    });
}


function showNav() {
    $("a#myRequestsNavButton, a#driversNavButton, " + 
      "a#vehiclesNavButton, a#reportsNavButton, " +
      "a#optionsNavButton, a#logoutNavButton, " +
      "div.contentControls, span#commitmentTab, " +
      "span#timelineTab")
        .show();
    $("#sectionTitle")
        .attr("alt","My Requests section")
        .attr("src","/tmpo/images/myrequests_hd.gif");
}


function buildForm() {
    $("div.mainContent").append( proto_html['form_248'] );
    $.ajax({
        type: "GET",
        url: "/api/tmpo/role_check/",
        async: false,
        success: function() {
            showNav();
            $("#button_add_legs_guest").remove();
            $("#button_add_legs_dispatcher").show();
            $("div.mainContent table.form tbody:last tr:last td:first")
                .append( proto_html['itinerary_dispatcher'] );
            if ( $.qs('commitment_id') ){
                getItem( $.qs('commitment_id') );
            }else{
                $("table[name='itinerary']")
                    .append( proto_html['leg_dispatcher'] );
                $("div.mainContent table.form")
                    .append( proto_html['buttons_add_dispatcher'] );
                bindButtons();
                bindRows();
                bindDeletes();
		bindAutos();
                maybeCookieFill();
            }
        },
        error: function() {
//            $("td:contains('Support of:')").html('&nbsp;');
            $("#button_add_legs_guest").show();
            $("#button_add_legs_dispatcher").remove();
            $("div.mainContent table.form tbody:last tr:last td:first")
                .append( proto_html['itinerary_guest'] );
            $("table[name='itinerary']")
                .append( proto_html['leg_guest'] );
            $("div.mainContent table.form")
                .append( proto_html['buttons_guest'] );
            bindButtons();
            bindRows();
            bindDeletes();
        }
    });
}


var addRequestedCommitment = function() {
    var url = '/api/tmpo/commitment/requested/';
    var request_method = 'PUT';
    var data = commitmentData();
    var sc = function(json) {
        addRequestedLegs(json);
    };
    var ec = function() {
	$("#button_submit").siblings("span").hide();
	$("#button_submit").siblings("span:eq(0)").show();
        bindButtons();
        bindRows();
        bindDeletes();
    };
    return makeSubmit(url, request_method, data, sc, ec);
}


var addCommitment = function() {
    var url = '/api/tmpo/commitment/resourced/';
    var request_method = 'PUT';
    var data = commitmentData();
    var sc = function(json) {
        addLegs(json);
    };
    var ec = function() {
	$("#button_save_add").siblings("span").hide();
	$("#button_save_add").siblings("span:eq(0)").show();
        bindButtons();
        bindRows();
        bindDeletes();
    };
    return makeSubmit(url, request_method, data, sc, ec);
}


var updateCommitment = function(commitment_id) {
    var url = '/api/tmpo/commitment/resourced/' + commitment_id + '/';
    var request_method = 'POST';
    var data = commitmentData();
    var sc = function() {
        deleteLegs(commitment_id);
    };
    var ec = function() {
	$("#button_save_edit").siblings("span").hide();
	$("#button_save_edit").siblings("span:eq(0)").show();
        bindButtons(commitment_id);
        bindRows();
        bindDeletes();
    };
    return makeSubmit(url, request_method, data, sc, ec);
}


var cancelCommitment = function(commitment_id) {
    var url = '/api/tmpo/commitment/' + commitment_id + '/';
    var request_method = 'DELETE';
    var data = {};
    var sc = function() {
        notifyMessage( commitment_id);
    };
    var ec = function() {
	$("#button_delete").siblings("span").hide();
	$("#button_delete").siblings("span:eq(0)").show();
        bindButtons(commitment_id);
        bindRows();
        bindDeletes();
    };
    return makeSubmit(url, request_method, data, sc, ec);
}


var deleteLegs = function(commitment_id) {
    var url = '/api/tmpo/commitment/leg/' + commitment_id + '/';
    var request_method = 'DELETE';
    var data = {};
    var sc = function() {
        addLegs(commitment_id);
    };
    var ec = function() {
        console.debug('Error Deleting Legs');
    };
    return makeSubmit(url, request_method, data, sc, ec);
}


function makeSubmit(url, request_method, data, sc, ec) {
    $.ajax({
        url: url,
        type: request_method,
        data: data,
        async: true,
        dataType: "json",
        success: sc,
        error: ec
    });
}


function getItem(commitment_id) {
    $.ajax({
        type: "GET",
        url: '/api/tmpo/commitment/' + commitment_id + '/',
        async: true,
        dataType: "json",
        success: function(json) {
            fillForm(json);
            $("div.mainContent table.form")
                .append( proto_html['buttons_edit_dispatcher'] );
            bindButtons(commitment_id);
            bindRows();
            bindDeletes();            
        },
        error: function(){
            console.debug('Failed to load commitment.');
        }
    });
}


function addRequestedLegs(commitment_id) {    
    var legs = $("table[name='itinerary'] tbody:has(span)");
    jQuery.each(legs, function(i) {
        if( (i + 1) == legs.length ){
            var success = function() {
                notifyMessage(commitment_id);
	    }	
	}else{
            var success = function() {}
	}
        $.ajax({
            type: "PUT",
            url: '/api/tmpo/commitment/requested/leg/' + commitment_id + '/',
            data: legData(this),
            dataType: "json",
	    success: success
        });        
    });
    
}


function addLegs(commitment_id) {
    var legs = $("table[name='itinerary'] tbody:has(span)");
    jQuery.each(legs, function(i) {
        if( (i + 1) == legs.length ){
            var success = function() {
                notifyMessage(commitment_id);
	    }	
	}else{
            var success = function() {}
	}
        $.ajax({
            type: "PUT",
            url: '/api/tmpo/commitment/leg/' + commitment_id + '/',
            data: legData(this),
            dataType: "json",
	    success: success
        });
    });
}


function legData(leg) {
    var ret = {};
    var date = $(leg).find(":input[name='date']").val();

    var checkin = $(leg).find(":input[name='checkin_time']").val();
    ret['checkin'] = $.d2m3y4_to_y4m2d2(date) + ' ' +
                   checkin.substr(0,2) + ':' + checkin.substr(2,2);

    var start = $(leg).find(":input[name='start_time']").val();
    ret['start'] = $.d2m3y4_to_y4m2d2(date) + ' ' +
                   start.substr(0,2) + ':' + start.substr(2,2);
    var finish = $(leg).find(":input[name='finish_time']").val();
    ret['finish'] = $.d2m3y4_to_y4m2d2(date) + ' ' +
                    finish.substr(0,2) + ':' + finish.substr(2,2);
    ret['location'] = $(leg).find(":input[name='location']").val();
    ret['destination'] = $(leg).find(":input[name='destination']").val();
    ret['passengers'] = ( $(leg).find(":input[name='passengers']").val() )
                      ? $(leg).find(":input[name='passengers']").val()
		      : 0 ;
    ret['cargo'] = $(leg).find(":input[name='cargo']").val();
    ret['comment'] = $(leg).find(":input[name='comment']").val();
    var sel = $(leg).find("span[name='vehicles'] :checkbox:checked");
    var vehicles = ['0'];
    jQuery.each(sel, function(i, v) {
        vehicles[i+1] = $(this).val();
    });
    ret['vehicles'] = vehicles;
    sel = $(leg).find("span[name='drivers'] :checkbox:checked");
    var drivers = ['0'];
    jQuery.each(sel, function(i, v) {
        drivers[i+1] = Number($(this).val());
    });
    ret['drivers'] = drivers;
    return ret;
}


function addDispatcherLegs(val) {
    jQuery.each(Array(val), function() {
        $("table[name='itinerary']")
             .append( proto_html['leg_dispatcher'] );
    });
    bindRows();
    bindDeletes();
}


function addGuestLegs(val) {
    jQuery.each(Array(val), function() {
        $("table[name='itinerary']")
             .append( proto_html['leg_guest'] );
    });
    bindRows();
    bindDeletes();
}


function fillForm(json) {
    jQuery.each(json, function(k, v) {
        if ( !v ){
            json[k] = '';
        }
    });
    var fields = ['requested_by','poc_smtp','trans_coord_name',
                  'org_req_name','purpose','poc_name','deliver_post'];
    jQuery.each(fields, function() {
        $(":input#" + this).val( json[this] );
    });
    fields = ['requester_phone',
              'trans_coord_phone',
              'org_req_phone',
              'poc_phone',
              'poc_alt_phone'];
    jQuery.each(fields, function() {
        $(":input#" + this + "_area").val( json[this].substr(0,3) );
        $(":input#" + this + "_prefix").val( json[this].substr(3,3) );
        $(":input#" + this + "_suffix").val( json[this].substr(6,4) );
    });
    if ( !json['wait'] ){
        $(":input[name='wait']").removeAttr("checked");
        $(":input[name='wait'][value='0']").attr("checked","checked");
    }
    $("#fund_cite option[value='" + json['fund_cite'] + "']")
        .attr("selected","selected");
    if ( json['legs'].length ){
        fields = ['location','destination','passengers','cargo','comment'];
        jQuery.each(json['legs'], function() {
            var leg = this;
            $("table[name='itinerary']")
                .append( proto_html['leg_dispatcher'] );
            var sel = "table[name='itinerary'] tbody:last";
            var val = $.y4m2d2_to_d2m3y4( leg['start'].substr(0,10) );
            $(sel + " :input[name='date']").val( val );

            val = leg['checkin'];
            if (val != null) {
                val = val.substr(11,2) + leg['checkin'].substr(14,2);
            } else {
                val = '';
            }
            $(sel + " :input[name='checkin_time']").val( val );

            val = leg['start'].substr(11,2) + leg['start'].substr(14,2);
            $(sel + " :input[name='start_time']").val( val );


            val = leg['finish'].substr(11,2) + leg['finish'].substr(14,2);
            $(sel + " :input[name='finish_time']").val( val );
            jQuery.each(fields, function() {
                $(sel + " :input[name='" + this + "']").val( leg[this] );
            });
            var span = sel + " span[name='drivers']";
            var labels = [];
            jQuery.each(leg['drivers'], function() {
                var cb = $(span + " :checkbox[value='" + this + "']");
                $(cb).attr("checked","checked");
                labels[ labels.length ] = $(cb).attr('label');
            });
            labels = labels.length ? labels.join(', ') : 'None.';
            $(span).siblings("span[name='list']").html(labels);
            span = sel + " span[name='vehicles']";
            labels = [];
            jQuery.each(leg['vehicles'], function() {
                var cb = $(span + " :checkbox[value='" + this + "']");
                $(cb).attr("checked","checked");
                labels[ labels.length ] = $(cb).attr('label');
            });
            labels = labels.length ? labels.join(', ') : 'None.';
            $(span).siblings("span[name='list']").html(labels);
        });
    }else{
        $("table[name='itinerary']")
            .append( proto_html['leg_dispatcher'] );
    }
}


function commitmentData() {
    var ret = {};
    var fields = ['requested_by','poc_smtp','trans_coord_name','org_req_name',
                  'fund_cite','purpose','poc_name','deliver_post'];
    jQuery.each(fields, function() {
        if( $(":input#" + this).length ){
            ret[this] = $(":input#" + this).val();
        }
    });
    fields = ['requester_phone','trans_coord_phone','org_req_phone',
              'poc_phone','poc_alt_phone'];
    jQuery.each(fields, function() {
        ret[this] = $(":input#" + this + "_area").val() +
                    $(":input#" + this + "_prefix").val() +
                    $(":input#" + this + "_suffix").val();
    });
    ret['wait'] = $(":input[name='wait']:checked").val();
    return ret;
}


function bindButtons(commitment_id) {
    $("table.form a.button").unbind();
    $("#button_add_legs_dispatcher").click( function() {
        var val = $("input[name='leg_count']").val();
        if( /^\d+$/.test(val) && val > 0 ){
            addDispatcherLegs(Number(val));
        }
        return false;
    });
    $("#button_add_legs_guest").click( function() {
        var val = $("input[name='leg_count']").val();
        if( /^\d+$/.test(val) && val > 0 ){
            addGuestLegs(Number(val));
        }
        return false;
    });
    $("#button_submit").click( function() {
        $("table.form *").unbind();
	$(this).siblings("span").hide();
	$(this).siblings("span:eq(2)").show();
        if( !validateForm() ){
            addRequestedCommitment();
        }else{
            $(this).siblings("span").hide();
	    $(this).siblings("span:eq(1)").show();
            bindButtons();
            bindRows();
            bindDeletes();
        }
        return false;	
    });
    $("#button_save_add").click( function() {
        $("table.form *").unbind();
	$(this).siblings("span").hide();
	$(this).siblings("span:eq(2)").show();
        if( !validateForm() ){
            addCommitment();
        } else {
            $(this).siblings("span").hide();
	    $(this).siblings("span:eq(1)").show();
            bindButtons();
            bindRows();
            bindDeletes();
        }
        return false;	
    });
    $("#button_save_edit").click( function() {
        $("table.form *").unbind();
	$(this).siblings("span").hide();
	$(this).siblings("span:eq(2)").show();
        if( !validateForm() ){
            updateCommitment(commitment_id);
        }else{
            $(this).siblings("span").hide();
            $(this).siblings("span:eq(1)").show();
            bindButtons(commitment_id);
            bindRows();
            bindDeletes();
        }
        return false;	
    });
    $("#button_delete").click( function() {
        $("table.form *").unbind();
	$(this).siblings("span").hide();
	$(this).siblings("span:eq(2)").show();
        cancelCommitment(commitment_id);
        return false;
    });
    $("#button_cancel").click( function() {
        $("table.form *").unbind();
        history.back();
        return false;
    });
    $("#pocRequester").unbind();
    $("#pocRequester").click( function() {
        if( $("#pocRequester:checked").length ){
            $(":input#poc_name")
                .val( $(":input#requested_by").val() );
            $(":input#poc_phone_area")
                .val( $(":input#requester_phone_area").val() );
            $(":input#poc_phone_prefix")
                .val( $(":input#requester_phone_prefix").val() );
            $(":input#poc_phone_suffix")
                .val( $(":input#requester_phone_suffix").val() );
        }
    });
}


function bindDeletes() {
    $("table[name='itinerary'] tbody span[name='span_delete']")
        .unbind()
        .click( function() {
            if( $("table[name='itinerary'] tbody:has(span)").length > 1 ){
                $(this).parents("tbody:first").remove();
            }else{
                $(this).parents("tbody:first")
                    .find(":input:not(:checkbox)").val('');
                $(this).parents("tbody:first")
                    .find(":checkbox").removeAttr('checked');
                $(this).parents("tbody:first")
                    .find("span[name='list']").html('None');
            }
            return false;
        });
}


function bindRows() {
    var sel = "table[name='itinerary'] tbody";
    $(sel).unbind();
    $(sel).hover(
        function() {
            $(this).addClass('highlight');
        },
        function() {
            $(this).removeClass('highlight');
        }
    );
    sel = "table[name='itinerary'] tbody span[name='drivers'], " +
          "span[name='vehicles']";
    sel = $(sel).children(":checkbox");
    $(sel).unbind();
    $(sel).click( function() {
        var sel = $(this).parent().children(":checked");
        var labels = [];
        jQuery.each(sel, function(i, v) {
            labels[i] = $(this).attr('label');
        })
        labels = labels.length ? labels.join(', ') : 'None.';
        $(this).parent().siblings("span[name='list']").html(labels);
    });
}

function maybeFixFinish() {
    var legs = $("table[name='itinerary'] tbody:has(span)");
    jQuery.each(legs, function() {
        var leg = this;
	var start_time = $(leg).find(":input[name='start_time']").val();
        if ($(leg).find(":input[name='finish_time']").val() == "" && start_time != "") {
            $(leg).find(":input[name='finish_time']").val( ("0"+(Number(start_time)+1)).slice(-4,5))
	    }
    })
}

function validateForm() {
    var error_count = 0;
    maybeFixFinish();
    $("span.inputErrorMessage").hide();
    $("td.inputError").removeClass("inputError");
    var fields = ['requested_by','poc_smtp','trans_coord_name',
                  'org_req_name','poc_name','deliver_post'];
    jQuery.each(fields, function() {
        if( !jQuery.trim( $("#" + this).val() ) ){
            error_count++;
            $("#" + this).parents("td:first").addClass("inputError")
                .children("span:eq(1)").show();
        }
    });
    fields = ['requester_phone','trans_coord_phone','poc_phone'];
    jQuery.each(fields, function() {
        if( !jQuery.trim( $("#" + this + "_area").val() ) ||
            !jQuery.trim( $("#" + this + "_prefix").val() ) ||
            !jQuery.trim( $("#" + this + "_suffix").val() )
          ){
            error_count++;
            $("#" + this + "_area").parents("td:first")
                .addClass("inputError")
                .children("span:eq(2)").hide().end()
                .children("span:eq(1)").show();
        }else{
            var phone = jQuery.trim( $("#" + this + "_area").val() ) +
                        jQuery.trim( $("#" + this + "_prefix").val() ) +
                        jQuery.trim( $("#" + this + "_suffix").val() );                       
            var re = '^[0-9]{10}$';
            if( !phone.match(new RegExp(re)) ){
                error_count++;
                $("#" + this + "_area").parents("td:first")
                    .addClass("inputError")
                    .children("span:eq(1)").hide().end()
                    .children("span:eq(2)").show();          
            }
        }
    });
    var legs = $("table[name='itinerary'] tbody:has(span)");
    var leg_fields = ['date','checkin_time','start_time','finish_time',
                      'location','destination'];
    jQuery.each(legs, function() {
        var leg = this;
        jQuery.each(leg_fields, function() {
            var f = $(leg).find(":input[name='" + this + "']");
            if( !jQuery.trim( $(f).val() ) ){
                error_count++;
                $(f).parents("td:first").addClass("inputError")
                    .children("span.inputErrorMessage:eq(2)").hide().end()
                    .children("span.inputErrorMessage:eq(1)").hide().end()
                    .children("span.inputErrorMessage:eq(0)").show();
            }
        });
	var f = $(leg).find(":input[name='passengers']");
	if( jQuery.trim( $(f).val() ) &&
	    !$(f).val().match(new RegExp('^[0-9]+$'))
	  ){
            error_count++;
            $(f).parents("td:first").addClass("inputError")
                .children("span:eq(0)").show();
	}
        f = $(leg).find(":input[name='date']");
        if( jQuery.trim( $(f).val() ) &&
            !jQuery.is_d2m3y4( $(f).val() ) 
          ){
            error_count++;
            $(f).parents("td:first").addClass("inputError")
                .children("span.inputErrorMessage:eq(0)").hide().end()
                .children("span.inputErrorMessage:eq(1)").show();
        }
	var start_time = $(leg).find(":input[name='start_time']");
        if( jQuery.trim( $(start_time).val() ) &&
	    !jQuery.is_24hour( $(start_time).val() )
	  ){
            error_count++;
            $(start_time).parents("td:first").addClass("inputError")
                .children("span.inputErrorMessage:eq(0)").hide().end()
                .children("span.inputErrorMessage:eq(1)").show();
	}

	var finish_time = $(leg).find(":input[name='finish_time']");
        if( jQuery.trim( $(finish_time).val() ) &&
	    !jQuery.is_24hour( $(finish_time).val() )
	  ){
            error_count++;
            $(finish_time).parents("td:first").addClass("inputError")
                .children("span.inputErrorMessage:eq(0)").hide().end()
                .children("span.inputErrorMessage:eq(2)").hide().end()
                .children("span.inputErrorMessage:eq(1)").show();
	}
        if( jQuery.is_24hour( $(start_time).val() ) &&
	    jQuery.is_24hour( $(finish_time).val() ) &&
	    ( $(start_time).val() >= $(finish_time).val() )
	  ){
            error_count++;
            $(finish_time).parents("td:first").addClass("inputError")
                .children("span.inputErrorMessage:eq(0)").hide().end()
                .children("span.inputErrorMessage:eq(1)").hide().end()
                .children("span.inputErrorMessage:eq(2)").show();
	}        
    });
    return error_count;
}


function setProtoHTML() {    
    var proto_pre = {
        'buttons_guest':'protoPublicButtonsHTML',
        'buttons_add_dispatcher':'protoDispatcherAddButtonsHTML',
        'buttons_edit_dispatcher':'protoDispatcherEditButtonsHTML',
        'leg_guest':'protoPublicItineraryLegHTML',
        'leg_dispatcher':'protoDispatcherItineraryLegHTML',
        'itinerary_guest':'protoPublicItineraryHTML',
        'itinerary_dispatcher':'protoDispatcherItineraryHTML',
        'form_248':'protoFormHTML'
    };
    proto_html = {};
    jQuery.each(proto_pre, function(i, val) {
        proto_html[i] = $("#" + val).html();
        $("#" + val).remove();
    });
}


function bindAutoSelect(fromEle, toEle) {
    mover = function(e) {
        maxlen = $("#"+fromEle).attr("maxlength");
        thislen = $("#"+fromEle).val().length;
        if (thislen >= maxlen) {
            $("#" + toEle).select();
        }
    }
    $("#"+fromEle).keyup(mover);
}


function testFormFill(e) {
    $("#requested_by").val("JOHN REQUESTOR");
    $("#poc_smtp").val("null@example.com");
    $("#requester_phone_area").val("907");
    $("#requester_phone_prefix").val("555");
    $("#requester_phone_suffix").val("1212");
    $("#trans_coord_name").val("JANE COORDINATOR");
    $("#trans_coord_phone_area").val("806");
    $("#trans_coord_phone_prefix").val("444");
    $("#trans_coord_phone_suffix").val("0101");
    $("#org_req_name").val("Any Org");
    $("#poc_name").val("JOHN STEPFORD");
    $("#poc_phone_area").val("705");
    $("#poc_phone_prefix").val("333");
    $("#poc_phone_suffix").val("2424");
    $("#deliver_post").val("TOAST");
    var d = new Date();
    $("[name=date]").val("" + padZero(d.getDay()) + " " +  convertMonthNum(d.getMonth()+1) + " " + d.getFullYear());
    $("[name=checkin_time]").val("0100");
    $("[name=start_time]").val("0130");
    $("[name=finish_time]").val("0200");
    $("[name=location]").val("LOCATION, LOCATION, LOCATION");
    $("[name=destination]").val("YONDER");
}

jQuery(function($) {
    getSiteCfg();
    getCommonLookups();
    $(".blazon img").dblclick(testFormFill);


    $(":radio, :checkbox").css("border", "none");
    $("#logoutNavButton").click( function() {
        $.post("/api/logout/", {},
            function() {
                window.location.href = "/tmpo/";   
            }
        );
    });
});


function bindAutoDate(selector) {
return;
    $(selector).blur(function (e) {
        var v = $(selector).val()
        var sv = v.split(/\W+/).filter(function (f) { return (!!f) })
        if (sv[0]) {
            if (sv[0].length==1) {sv[0]="0"+sv[0]}
        }
        if (!sv[2]) {
            sv[2] = "" + new Date().getFullYear();
        }
        $(selector).val(sv.join(" "))
    })
}


function bindAutoTime(selector) {
    $(selector).blur(function (e) {
        var v = $(selector).val()
        if (v.length==3) { $(selector).val("0" + v)}
    })
}



function bindAutos() {
    bindAutoSelect("requester_phone_area", "requester_phone_prefix");
    bindAutoSelect("requester_phone_prefix", "requester_phone_suffix");
    bindAutoSelect("requester_phone_suffix", "trans_coord_name");

    bindAutoSelect("trans_coord_phone_area", "trans_coord_phone_prefix");
    bindAutoSelect("trans_coord_phone_prefix", "trans_coord_phone_suffix");
    bindAutoSelect("trans_coord_phone_suffix", "org_req_name");

    bindAutoSelect("org_req_phone_area", "org_req_phone_prefix");
    bindAutoSelect("org_req_phone_prefix", "org_req_phone_suffix");
    bindAutoSelect("org_req_phone_suffix", "fund_cite");

    bindAutoSelect("poc_phone_area", "poc_phone_prefix");
    bindAutoSelect("poc_phone_prefix", "poc_phone_suffix");
    bindAutoSelect("poc_phone_suffix", "poc_alt_phone_area");

    bindAutoSelect("poc_alt_phone_area", "poc_alt_phone_prefix");
    bindAutoSelect("poc_alt_phone_prefix", "poc_alt_phone_suffix");
    bindAutoSelect("poc_alt_phone_suffix", "deliver_post");

    bindAutoDate("[name=date]");
    bindAutoTime("[name=checkin_time]");
    bindAutoTime("[name=start_time]");
    bindAutoTime("[name=finish_time]");

}


function fillValue(src, map) {
    $("#"+src).attr("value", map[src]);
}


function fillSelect(src, map) {
    $("#" + src + " option[text="+ map[src] +"]").attr("selected", true)
}


function fillCheck(src, map) {
    var v = map[src] ? 1 : 0;
    $("[name=" + src + "][value='" + v + "']").attr("checked", true)
}


function fillPhone(src, map) {
    var parts = [['_area',0,3], ['_prefix',3,3], ['_suffix',6,4]]
    var num = map[src];
    for (var part in parts) {
        part = parts[part]
        var sfx = part[0]; var start = part[1]; var finish = part[2];
        $("#" + src + sfx).attr("value", num.substr(start, finish));
    }
}


function fillLegTime(ds, target) {
    var t = ds.split(" ")[1].split(":")[0] + ds.split(" ")[1].split(":")[1];
    target.attr("value", t)
}


function fillLegSelect(vals, target) {
    target.filter(function(idx) {
        return $.inArray(Number($(this).attr("value")), vals  ) > -1
    }).attr("checked", true)
}


function fillLegs(src, map) {
    var legs = map[src];
    for (index in legs) {
        var leg = legs[index];
        if (index>0) {
            addDispatcherLegs(1);
        }
        var form = $("table[name=itinerary] tbody:last");
        // we don't copy "date" from the template because that doesn't
        // make sense
        fillLegTime(leg["checkin"], $("input[name=checkin_time]", form));
        fillLegTime(leg["start"], $("input[name=start_time]", form));
        fillLegTime(leg["finish"], $("input[name=finish_time]", form));
        fillLegSelect(leg["drivers"], $("span[name=drivers] input[type=checkbox]", form))
        fillLegSelect(leg["vehicles"], $("span[name=vehicles] input[type=checkbox]", form))
        $("input[name=destination]", form).attr("value", leg["destination"]);
        $("input[name=location]", form).attr("value", leg["location"]);
        $("input[name=passengers]", form).attr("value", leg["passengers"]);
        $("textarea[name=comment]", form).text(leg["comment"]);
    }
}


fillFunctions = {
    deliver_post:fillValue,
    org_req_name:fillValue,
    poc_name:fillValue,
    poc_smtp:fillValue,
    purpose:fillValue,
    requested_by:fillValue,
    trans_coord_name:fillValue,
    wait:fillCheck,
    org_req_phone:fillPhone,
    poc_alt_phone:fillPhone,
    poc_phone:fillPhone,
    requester_phone:fillPhone,
    trans_coord_phone:fillPhone,
    legs:fillLegs,
    fund_cite:fillSelect
}


function maybeCookieFill () {
    var ct = $.qs("ct");
    if (ct) {
        var jv = $.parseJSON($.cookie(templateCookiePrefix + ct));
        var key = "";
        for (key in jv) {
            if (key in fillFunctions) {
                fillFunctions[key](key, jv);
            }
        }
    }
}
